import sys argv = sys.argv narg = len(argv) if narg <= 3: print("") print("Usage: python {} val base_source base_target".format(argv[0])) print("") exit() else: val = argv[1] base_source = int(argv[2]) base_target = int(argv[3]) base_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" max_base = len(base_chars) if base_source > max_base: print("") print("Error: base_source [{}] is too large.".format(base_source)) print("") exit() if base_target > max_base: print("") print("Error: base_target [{}] is too large.".format(base_target)) print("") exit() def value_base(char, b): return list(base_chars).index(char.upper()) print("") print(f"Convert {val} in base {base_source} to base 10") nstr = len(val) v10 = 0 for i in range(nstr): idx = nstr - 1 - i v = value_base(val[idx], base_source) if v >= base_source: print(f"Error: The value at the {i}-th digit {v} is not compatible with base {base_source}") exit() dv = v * base_source**i v10 += dv print(f"{i}-th digit = {v}_{base_source}: + {v}*{base_source}^{i} => + {dv:10}_10 => {v10:10}_10") b10 = str(v10) print("") print(f"Convert {b10} in base 10 to base {base_target}") vnext = v10 starget = '' while 1: n = int(vnext / base_target) residue = vnext % base_target starget = base_chars[residue] + starget print("{:10} = {:10} * {:10} + {:2}:".format(vnext, n, base_target, residue), end = '') print(" base_{} => {}".format(base_target, starget)) if n == 0: break vnext = n print("")